import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { ElMessage } from 'element-plus';

/**
 * 导出工具类
 */
export class ExportUtils {
  /**
   * 将DOM元素导出为图片
   * @param element DOM元素或选择器
   * @param filename 文件名（不含扩展名）
   * @param options 配置选项
   */
  static async exportToImage(
    element: HTMLElement | string,
    filename: string = 'export',
    options: {
      format?: 'png' | 'jpeg';
      quality?: number;
      scale?: number;
      backgroundColor?: string;
    } = {}
  ): Promise<void> {
    try {
      const {
        format = 'png',
        quality = 0.92,
        scale = 2,
        backgroundColor = '#ffffff'
      } = options;

      // 获取DOM元素
      const targetElement = typeof element === 'string' 
        ? document.querySelector(element) as HTMLElement
        : element;

      if (!targetElement) {
        throw new Error('未找到目标元素');
      }

      ElMessage.info('正在生成图片，请稍候...');

      // 使用html2canvas截图
      const canvas = await html2canvas(targetElement, {
        scale,
        backgroundColor,
        useCORS: true,
        allowTaint: true,
        logging: false,
        width: targetElement.scrollWidth,
        height: targetElement.scrollHeight,
      });

      // 创建下载链接
      const link = document.createElement('a');
      link.download = `${filename}.${format}`;
      
      if (format === 'jpeg') {
        link.href = canvas.toDataURL('image/jpeg', quality);
      } else {
        link.href = canvas.toDataURL('image/png');
      }
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success('图片导出成功！');
    } catch (error) {
      console.error('导出图片失败:', error);
      ElMessage.error('导出图片失败，请重试');
      throw error;
    }
  }

  /**
   * 将DOM元素导出为PDF
   * @param element DOM元素或选择器
   * @param filename 文件名（不含扩展名）
   * @param options 配置选项
   */
  static async exportToPDF(
    element: HTMLElement | string,
    filename: string = 'export',
    options: {
      orientation?: 'portrait' | 'landscape';
      unit?: 'mm' | 'cm' | 'in' | 'px';
      format?: 'a4' | 'a3' | 'a5' | 'letter' | 'legal';
      scale?: number;
      backgroundColor?: string;
      margin?: {
        top?: number;
        right?: number;
        bottom?: number;
        left?: number;
      };
    } = {}
  ): Promise<void> {
    try {
      const {
        orientation = 'portrait',
        unit = 'mm',
        format = 'a4',
        scale = 2,
        backgroundColor = '#ffffff',
        margin = { top: 10, right: 10, bottom: 10, left: 10 }
      } = options;

      // 获取DOM元素
      const targetElement = typeof element === 'string' 
        ? document.querySelector(element) as HTMLElement
        : element;

      if (!targetElement) {
        throw new Error('未找到目标元素');
      }

      ElMessage.info('正在生成PDF，请稍候...');

      // 使用html2canvas截图
      const canvas = await html2canvas(targetElement, {
        scale,
        backgroundColor,
        useCORS: true,
        allowTaint: true,
        logging: false,
        width: targetElement.scrollWidth,
        height: targetElement.scrollHeight,
      });

      // 创建PDF文档
      const pdf = new jsPDF({
        orientation,
        unit,
        format,
      });

      // 获取PDF页面尺寸
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();

      // 计算图片在PDF中的尺寸
      const imgWidth = pdfWidth - (margin.left || 0) - (margin.right || 0);
      const imgHeight = (canvas.height * imgWidth) / canvas.width;

      // 如果图片高度超过页面高度，需要分页
      if (imgHeight > pdfHeight - (margin.top || 0) - (margin.bottom || 0)) {
        const pageHeight = pdfHeight - (margin.top || 0) - (margin.bottom || 0);
        const totalPages = Math.ceil(imgHeight / pageHeight);

        for (let i = 0; i < totalPages; i++) {
          if (i > 0) {
            pdf.addPage();
          }

          const yOffset = -(i * pageHeight * canvas.width) / imgWidth;
          
          pdf.addImage(
            canvas.toDataURL('image/jpeg', 0.95),
            'JPEG',
            margin.left || 0,
            margin.top || 0,
            imgWidth,
            imgHeight
          );
        }
      } else {
        // 单页PDF
        pdf.addImage(
          canvas.toDataURL('image/jpeg', 0.95),
          'JPEG',
          margin.left || 0,
          margin.top || 0,
          imgWidth,
          imgHeight
        );
      }

      // 保存PDF
      pdf.save(`${filename}.pdf`);

      ElMessage.success('PDF导出成功！');
    } catch (error) {
      console.error('导出PDF失败:', error);
      ElMessage.error('导出PDF失败，请重试');
      throw error;
    }
  }

  /**
   * 获取当前日期时间字符串（用于文件名）
   */
  static getDateTimeString(): string {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    return `${year}${month}${day}_${hours}${minutes}${seconds}`;
  }

  /**
   * 格式化文件名（移除特殊字符）
   */
  static sanitizeFilename(filename: string): string {
    return filename.replace(/[<>:"/\\|?*]/g, '_');
  }
} 